<?php
namespace Peas\Kernel\Inter;

use Peas\Config\Configure;
use Peas\Http\HttpUtils;
use Peas\Kernel\Helper\AesHelper;
use Peas\Kernel\System\ActionContext;

/**
 * Peas Framework
 *
 * 接口类辅助类
 *
 * @author  Hongzan Zhang <zhanghongzan@163.com>
 * @version $Id$
 */
class InterHelper
{
    /**
     * 存储结果编码
     *
     * @var array
     */
    private static $_codeMap = null;


    /**
     * 根据状态码获取描述信息
     *
     * @param  string $type       状态类型
     * @param  int    $statusCode 状态码
     * @return string
     */
    private static function _getCodeDesc($type, $statusCode)
    {
        if (self::$_codeMap === null) {
            self::$_codeMap = include _PATH . '/resources/inter/codeMap.php';
        }
        return isset(self::$_codeMap[$type][$statusCode]) ? self::$_codeMap[$type][$statusCode] : '';
    }


    /**
     * 获取成功状态InterCode
     *
     * @param  int $statusCode
     * @return \Peas\Kernel\Inter\InterCode
     */
    public static function getSuccessCode($statusCode = 10000)
    {
        return new InterCode(InterCode::STATUS_SUCCESS, $statusCode, self::_getCodeDesc(InterCode::STATUS_SUCCESS, $statusCode));
    }

    /**
     * 获取失败状态InterCode
     *
     * @param  int $statusCode
     * @return \Peas\Kernel\Inter\InterCode
     */
    public static function getFailureCode($statusCode = 20000)
    {
        return new InterCode(InterCode::STATUS_FAILURE, $statusCode, self::_getCodeDesc(InterCode::STATUS_FAILURE, $statusCode));
    }


    /**
     * 输出响应字符串，如果传入了callback参数则默认为jsonp方式，callback即为回调函数名
     *
     * @param  string $text
     * @return void
     */
    public static function printText($text)
    {
        ActionContext::$isPage = false;
        header('Content-Type: text/html; charset=' . Configure::get('_default.charset'));
        $callback = isset($_REQUEST['callback']) ? $_REQUEST['callback'] : '';
        echo empty($callback) ? $text : ($callback . '(' . $text . ');');
    }

    /**
     * 输出响应Code，{"status" : "", "code" : "", "desc" : "", "data" : {}}，如果传入了callback参数则默认为jsonp方式，callback即为回调函数名
     *
     * @param  InterCode $interCode
     * @return void
     */
    public static function printCode(InterCode $interCode)
    {
        self::printText(json_encode($interCode));
    }


    /**
     * 输出成功信息响应Code，直接从code配置中获取
     *
     * @param  int   $statusCode
     * @param  array $data
     * @return void
     */
    public static function success($statusCode, array $data = [])
    {
        $interCode = self::getSuccessCode($statusCode);
        $interCode->data = $data;
        self::printCode($interCode);
    }

    /**
     * 输出失败信息响应Code，直接从code配置中获取
     *
     * @param  int   $statusCode
     * @param  array $data
     * @return void
     */
    public static function failure($statusCode, array $data = [])
    {
        $interCode = self::getFailureCode($statusCode);
        $interCode->data = $data;
        self::printCode($interCode);
    }


    /**
     * 获取AES加密参数
     * 参数中需包含：key（AES加密IV），data（AES加密的数据），v（密钥版本号，可选）
     *
     * @return array
     */
    public static function getParamData()
    {
        $key = $_REQUEST['key'];
        $aesData = $_REQUEST['data'];
        $kv = isset($_REQUEST['v']) ? $_REQUEST['v'] : null;

        if (empty($key) || empty($aesData)) {
            return [];
        }
        $dataStr = AesHelper::cbcDecode($aesData, $key, $kv);
        return json_decode($dataStr, true);
    }


    /**
     * 向指定接口发送请求
     *
     * @param  string $url   接口地址
     * @param  array  $param data参数数组
     * @param  string $kv    密钥版本号
     * @return mixed
     */
    public static function interRequest($url, array $param, $kv)
    {
        $iv = AesHelper::createTimeIv();
        $data = AesHelper::cbcEncode(json_encode($param), $iv, $kv);
        return HttpUtils::post($url, ['key' => $iv, 'data' => $data, 'v' => $kv]);
    }
}
